import { createDynamisRouter } from "@/router/dynamic-routes"
import { isEmpty } from "@/utils"
import { RouteRecordRaw } from "vue-router"

export interface UserState {
    name?: string
    avatar?: string
    gender?: string
}

export interface MenuState {
    // 编码
    code?: string
    // 显示名称
    name: string
    // 图标
    icon?: string
    // 访问路径
    path: string
    // 重定向
    redirect?: string
    // 组件位置
    component: string
    // 是否显示在菜单列表
    show?: boolean
    // 子菜单
    children?: MenuState[]
    // 自定义 meta
    meta?: Recordable
}

/**
 * 权限管理
 */
export const useAuthStore = defineStore("auth", () => {
    const userRef = shallowRef<UserState>({})
    const permissionsRef = shallowRef<string[]>([])
    const menusRef = shallowRef<RouteRecordRaw[]>()

    const isLogin = computed(() => !isEmpty(userRef.value))

    const hasPermission = (needPermission: string) => {
        const permissions = permissionsRef.value || []
        if (isEmpty(permissions)) {
            return false
        }
        return permissions.includes("*") || permissions.includes(needPermission)
    }

    const hasPermissions = (needPermissions: string[]) => {
        const permissions = permissionsRef.value || []
        if (isEmpty(permissions)) {
            return false
        }
        return needPermissions.some(value => hasPermission(value))
    }

    // 登录
    const login = async (user: UserState, permissions: string[], menus: MenuState[]) => {
        userRef.value = user
        permissionsRef.value = permissions
        menusRef.value = createDynamisRouter(menus ?? [], permissions)
    }

    // 登出
    const logout = async () => {
        userRef.value = {}
        permissionsRef.value = []
        menusRef.value = []
    }

    return {
        authInfo: userRef,
        isLogin,
        menus: menusRef,
        login,
        logout,
        hasPermission,
        hasPermissions
    }
})
